package com.lean.android.ad.core.reward

import android.app.Activity
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.lean.android.ad.core.AdLoadState
import com.lean.android.ad.core.AdLoader
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.core.ErrorCode
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt
import com.lean.android.ad.utils.AdLog
import java.util.UUID
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

@RestrictTo(RestrictTo.Scope.LIBRARY)
class RewardAdLoader : AdLoader {

    companion object {
        private fun getAdSlotRewardVideo(): AdSlot {
            return AdSlot.Builder().setCodeId(AdSdk.getAdConfig().adParamsProvider.getRewardAdId())
                .setOrientation(TTAdConstant.VERTICAL)//横竖屏设置
                .setMediationAdSlot(
                    MediationAdSlot.Builder().setMuted(false).setVolume(1f).setBidNotify(true)
                        .build()
                ).build()
        }
    }

    override suspend fun load(activity: Activity): AdLoadState {
        val requestId = UUID.randomUUID().toString()
        AdLog.d(AdLog.AdRewardLoadTag, "start to load reward ad, requestId $requestId.")
        AdLoaders.toast(activity, "加载中，请稍后~")
        return suspendCoroutine { coroutine ->
            val nativeLoader = TTAdSdk.getAdManager().createAdNative(activity)
            nativeLoader.loadRewardVideoAd(getAdSlotRewardVideo(),
                object : TTAdNative.RewardVideoAdListener {
                    override fun onError(code: Int, message: String) {
                        AdLog.e(
                            AdLog.AdRewardLoadTag,
                            "reward ad load failed, requestId $requestId , code $code, message $message."
                        )
                        AdLoaders.toast(activity, "广告加载失败，请重试~")
                        ReportHelper.reportAdEvent(
                            requestId = requestId,
                            eventType = ReportHelper.AdEventType.AdError,
                            adPosition = ReportHelper.AdPositionType.RewardVideo,
                            errorCode = code.toString()
                        )

                        coroutine.resume(AdLoadState.Error(ErrorCode.ErrorAdLoadFailed, message))
                    }

                    override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                        AdLog.d(
                            AdLog.AdRewardLoadTag, "reward ad load success, requestId $requestId."
                        )

                    }

                    override fun onRewardVideoCached() {

                    }

                    override fun onRewardVideoCached(ad: TTRewardVideoAd?) {
                        if (ad == null) {
                            AdLoaders.toast(activity, "广告加载失败，请重试~")
                            AdLog.e(
                                AdLog.AdRewardLoadTag,
                                "reward video cached, requestId $requestId , but ad is null."
                            )
                            coroutine.resume(
                                AdLoadState.Error(
                                    ErrorCode.ErrorAdLoadFailed, "reward ad is null."
                                )
                            )
                        } else {
                            AdLog.d(
                                AdLog.AdRewardLoadTag, "reward video cached, requestId $requestId."
                            )

                            ad.mediationManager?.bestEcpm?.also { cpmInfo ->
                                val cpm = cpmInfo.ecpm.toCpmInt()
                                ReportHelper.reportAdEvent(
                                    requestId = requestId,
                                    eventType = ReportHelper.AdEventType.AdLoaded,
                                    platformId = cpmInfo.sdkName.orEmpty(),
                                    adPosition = ReportHelper.AdPositionType.RewardVideo,
                                    cpm = cpm
                                )
                            }

                            coroutine.resume(AdLoadState.Success(RewardAd(ad, requestId)))
                        }
                    }
                })
        }
    }
}